from django.shortcuts import render

# Create your views here.
from django.views.generic import View
from book.models import BookInfo
from django.http import JsonResponse
import json

# Create your views here.
class BookListView(View):
    """
    查询所有图书、增加图书
    """
    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        },safe=False)

class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """
    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        book.delete()

        return JsonResponse({},status=204)


######################序列化#########################################
from book.serializers import BookInfoSerializer
from book.models import BookInfo
from book.models import PeopleInfo
#单个
# book = BookInfo.objects.get(id=4)
# serializer = BookInfoSerializer(book)

#结果集
# book = BookInfo.objects.all()
# serializer = BookInfoSerializer(book,many=True)

from book.models import PeopleInfo
from book.serializers import PeopleInfoSerializer,BookInfoSerializer
# person = PeopleInfo.objects.get(id=10)
# serializer = PeopleInfoSerializer(instance=person)
book = BookInfo.objects.get(id = 1)
serializer = BookInfoSerializer(book)
serializer.data

######################反序列化################################
#验证,保存
# from book.serializers import BookInfoSerializer
# data = {
#      'id':5,
#      'name': 'python高级',
#      'pub_date': '2020-1-1',
#      'readcount': 400,
#      'commentcount': 200
#  }
#
# serializer = BookInfoSerializer(data=data)
# serializer.is_valid(raise_exception=True)

#更新
from book.serializers import BookInfoSerializer
data = {
     'id':5,
     'name': 'python高级',
     'pub_date': '2020-1-1',
     'readcount': 400,
     'commentcount': 200
 }
from book.models import BookInfo
book = BookInfo.objects.get(id=5)
serializer = BookInfoSerializer(instance=book,data=data)
serializer.is_valid(raise_exception=True)

######################   模型化序列化器      ###########################
from book.serializers import BookInfoModelSerializer,PeopleInfoModelSerializer
from book.models import BookInfo,PeopleInfo
BookInfoModelSerializer()
data = {
    'book':1,
    'name': '靖弟弟',
    'password': '123456abc',
    'is_delete':True
}
person = PeopleInfo.objects.get(id=18)
p = PeopleInfoModelSerializer(instance=person,data=data)
p.is_valid(raise_exception=True)


################  保存多条数据         ####################
from book.serializers import BookInfoModelSerializer,PeopleInfoModelSerializer
from book.models import BookInfo,PeopleInfo
data = [
    {
        'book_id': 1,
        'name': '靖妹妹～～～',
        'password':'123456abc'
    },
    {
        'book_id': 1,
        'name': '靖表哥～～～',
        'password': '123456abc'
    }
]
s = PeopleInfoModelSerializer(data=data,many=True)
s.is_valid(raise_exception=True)

################ 保存一本书和n个数据 ##########
from book.serializers import BookInfoModelSerializer,PeopleInfoModelSerializer
from book.models import BookInfo,PeopleInfo
data = {
    'name': '离离原上草',
    'people': [
        {
            'name': '靖妹妹111',
            'password': '123456abc'
        },
        {
            'name': '靖表哥222',
            'password': '123456abc'
        }
    ]
}
s = BookInfoModelSerializer(data=data)
s.is_valid(raise_exception=True)